package api

import (
	"ginfast/app/mall/dto"
	"ginfast/app/mall/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"
)

// User 分类
type User struct {
}

// ListHandler 列表
func (User) ListHandler(c *ginx.Context) {
	var data []model.User
	err := orm.DbFind(&data)
	c.JSONWriteData(data, err)
}

// PageHandler 分页
func (User) PageHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	var data []model.User
	total, _ := p.DbModelWhere(&model.User{}).Find(&data)
	c.JSONWriteTotal(total, data)
}

// GetHandler 查询
func (User) GetHandler(c *ginx.Context) {
	util.QueryByID(&model.User{}, c)
}

// AddHandler 新增
func (User) AddHandler(c *ginx.Context) {
	var p model.User
	//获取参数
	err := c.MustBind(&p.UserOpt)
	if err != nil {
		return
	}
	err = orm.DbCreate(&p)
	c.JSONWriteError(err)
}

// UpdateHandler 修改
func (User) UpdateHandler(c *ginx.Context) {
	var p model.User
	//获取参数
	err := c.MustBind(&p.UserOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	c.JSONWriteError(err)
}

// UpdateStatusHandler 修改
func (User) UpdateStatusHandler(c *ginx.Context) {
	var p model.User
	//获取参数
	err := c.MustBind(&p.UserOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateFields(&p, "Status")
	c.JSONWriteError(err)
}

// DeleteHandler 删除
func (User) DeleteHandler(c *ginx.Context) {
	util.Deletes(&model.User{}, c)
}

func (o User) Routers(r *ginx.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.PUT("/status", o.UpdateStatusHandler)
}
